<template>
    <div class="wrap">
        <div class="wrap-util">
            <a-button type="primary" class="mr-10" @click="showModal">
                <PlusCircleOutlined/>
                新增
            </a-button>
        </div>
        <div class="table">
            <table>
                <thead>
                <tr>
                    <th>名称</th>
                    <th>路径</th>
                    <th>类型</th>
                    <th>封面</th>
                    <th>下载量</th>
                    <th>添加日期</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item,index) in list">
                    <td>{{item.name}}</td>
                    <td>{{item.fileName.substring(0,100)}}</td>
                    <td>{{item.type}}</td>
                    <td>
                        <a-image
                                :width="80"
                                :src="item.cover"
                                fallback=""
                        >
                        </a-image>
                    </td>
                    <td>{{item.downloadCount}}</td>
                    <td>{{item.created}}</td>
                    <td>
                        <a @click="">
                            <EditOutlined/>
                            编辑</a>
                        <a-divider type="vertical"/>
                        <a-popconfirm @confirm="deleteItem(item.id)" title="确定删除？" ok-text="删除" cancel-text="取消">
                            <a>
                                <DeleteOutlined/>
                                删除</a>
                        </a-popconfirm>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <div>
            <a-modal v-model:visible="visible" title="编辑" @ok="handleOk" okText="添加" cancelText="取消">
                <div style="margin-bottom: 5px;">
                    <a-input v-model:value="up.name" placeholder="名称"/>
                </div>
                <div style="margin-bottom: 5px;">
                    <a-input v-model:value="up.type" placeholder="类型"/>
                </div>
                <div style="margin-bottom: 5px;">
                    <a-upload-dragger
                            name="file"
                            :headers="headers"
                            :multiple="false"
                            :action="zipUploadPath"
                            @change="handleChange"
                    >
                        <p class="ant-upload-drag-icon">
                            <inbox-outlined></inbox-outlined>
                        </p>
                        <p class="ant-upload-text">Click or drag file to this area to upload</p>
                        <p class="ant-upload-hint">
                            Support for a single or bulk upload. Strictly prohibit from uploading company data or other
                            band files
                        </p>
                    </a-upload-dragger>
                </div>
                <div style="margin-bottom: 5px;">
                    <a-upload
                            :headers="headers"
                            name="file"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            :action="coverUploadPath"
                            :before-upload="beforeCoverUpload"
                            @change="coverHandleChange"
                    >
                        <img v-if="up.cover!=''" :src="img" style="width: 100px;height: 100px;" alt="avatar"/>
                        <div v-else>
                            <loading-outlined v-if="loading"></loading-outlined>
                            <plus-outlined v-else></plus-outlined>
                            <div class="ant-upload-text">封面上传</div>
                        </div>
                    </a-upload>
                </div>
            </a-modal>
        </div>
    </div>
</template>

<script>
    import {
        PlusCircleOutlined, EditOutlined, DeleteOutlined, InboxOutlined,
        LoadingOutlined, PlusOutlined
    } from "@ant-design/icons-vue"
    import {listDownloadFile} from "../../../api/comms";
    import {getUserInfo, parseDatetime} from "../../../utils/util";
    import {addDownloadFile, deleteDownloadFile} from "../../../api/admin";
    import {message} from "ant-design-vue";

    function getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }


    export default {
        name: "File",
        components: {
            PlusCircleOutlined,
            EditOutlined,
            DeleteOutlined,
            InboxOutlined,
            LoadingOutlined,
            PlusOutlined
        },
        data() {
            return {
                list: [],
                visible: false,
                zipUploadPath: "",
                coverUploadPath: "",
                loading: false,
                img: "",
                headers: {
                    token: ""
                },
                up: {
                    name: "",
                    filePath: "",
                    cover: "",
                    type: "学习资料",
                }
            }
        },
        created() {
            this.initData();
            this.zipUploadPath = window.apiPath + "/file/zipUpload"
            this.coverUploadPath = window.apiPath + "/file/imageUpload"
            this.headers.token = getUserInfo().token;
        },
        methods: {
            initData() {
                listDownloadFile("学习资料").then(resp => {
                    this.list = resp.data;
                    this.list.forEach((item, index) => {
                        item.created = parseDatetime(item.created)
                        item.cover = window.apiPath + item.cover;
                    })
                })
            },
            deleteItem(id) {
                deleteDownloadFile(id).then(resp => {
                    if (resp.code == 200) {
                        message.success("已删除")
                        this.initData();
                    } else {
                        message.success(resp.message)
                    }
                })
            },
            showModal() {
                this.visible = true;
            },
            handleOk() {
                if (this.up.name == '') {
                    message.warn("不能为空");
                    return false;
                }
                this.visible = false;
                addDownloadFile(this.up.name, this.up.filePath, this.up.cover, this.up.type)
                    .then(resp => {
                        if (resp.code == 200) {
                            message.success("添加成功！");
                        }
                        this.initData();
                    })
            },
            handleChange(info) {
                const status = info.file.status;
                if (status !== 'uploading') {
                    //console.log(info.file, info.fileList);
                }
                if (status === 'done') {
                    message.success(`${info.file.name} 文件上传成功.`);
                    console.log(info.file.response.data.relativePath);
                    this.up.filePath = info.file.response.data.relativePath;
                } else if (status === 'error') {
                    message.error(`${info.file.name} 文件上传失败.`);
                }
            },
            beforeCoverUpload(file) {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

                if (!isJpgOrPng) {
                    message.error('You can only upload JPG file!');
                }

                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isLt2M) {
                    message.error('Image must smaller than 2MB!');
                }

                return isJpgOrPng && isLt2M;
            },
            coverHandleChange(info) {
                if (info.file.status === 'uploading') {
                    this.loading = true;
                    return;
                }

                if (info.file.status === 'done') {
                    // Get this url from response in real world.
                    getBase64(info.file.originFileObj, base64Url => {
                        this.up.cover = base64Url;
                        this.loading = false;
                        this.up.cover = info.file.response.data.relativePath;
                        this.img = window.apiPath + info.file.response.data.relativePath;
                    });
                }

                if (info.file.status === 'error') {
                    this.loading = false;
                    message.error('upload error');
                }
            }
        }
    }
</script>

<style scoped>

</style>